package com.itheima.config;

import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.common.ThreadCommon;
import com.itheima.pojo.Employee;
import com.itheima.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@Configuration
public class FilterController implements Filter {
    //获取过滤器
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        //获url地址
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String[] loginUrls = {"/employee/login","/user/login","/user/sendMsg","/employee/logout", "/backend/**", "/front/**"};
        String path1 = httpServletRequest.getRequestURI();
        for (String url : loginUrls) {
            if (antPathMatcher.match(url, path1)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        //手机端用户登录
        User user = (User) httpServletRequest.getSession().getAttribute("user");
        if(user!=null){
            ThreadCommon.setTableLogic(user.getId());
            //log.info("sssssssssssssssssssssssssss"+user.getId());
            filterChain.doFilter(request, response);
            return;
        }
        //商家端用户登录
        Employee employee = (Employee) httpServletRequest.getSession().getAttribute("employee");
        if (employee != null) {
            ThreadCommon.setTableLogic(employee.getId());
            filterChain.doFilter(request, response);
            return;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }
}
